<template>
  <el-dialog
    v-el-drag-dialog
    :title="title"
    :visible.sync="visible"
    width="1400px"
    @closed="reset"
  >
    <el-form
      ref="dataForm"
      :inline="true"
      :rules="rules"
      label-width="100px"
      :model="form"
    >
      <el-form-item v-if="model !== 'edit'" label="调拨单号">
        <el-input v-model="form.stockTransCode" clearable disabled />
      </el-form-item>

      <el-form-item label="调拨类型" prop="transType">
        <el-select
          v-model="form.transType"
          placeholder="请选择"
          :disabled="model === 'info'"
        >
          <el-option label="内部调拨" :value="1" />
          <el-option label="充装调拨" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="model !== 'edit'" label="申请人">
        <el-input v-model="form.applicant" clearable disabled />
      </el-form-item>
      <el-form-item v-if="model !== 'edit'" label="创建时间">
        <el-date-picker v-model="form.createTime" type="date" disabled />
      </el-form-item>
      <el-form-item label="仓库(出)" prop="outStoreId">
        <el-select
          v-model="form.outStoreId"
          placeholder="请选择"
          :disabled="model === 'info'"
        >
          <el-option
            v-for="item in storeMap"
            :key="item.storeId"
            :label="item.rName"
            :value="item.storeId"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="model == 'edit'" :table-form-merge="0.3">
        <el-button
          circle
          type="primary"
          :disabled="model === 'info'"
        ><svg-icon
          class="map"
          icon-class="exchange"
          @click="exchange"
        /></el-button>
      </el-form-item>
      <el-form-item label="仓库(入)" prop="inStoreId">
        <el-select
          v-model="form.inStoreId"
          placeholder="请选择"
          :disabled="model === 'info'"
        >
          <el-option
            v-for="item in storeMap"
            :key="item.storeId"
            :label="item.rName"
            :value="item.storeId"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="model !== 'edit'" label="审核人">
        <el-input v-model="form.checkUser" clearable disabled />
      </el-form-item>
      <el-form-item v-if="model !== 'edit'" label="审核时间">
        <el-date-picker v-model="form.createTime" type="date" disabled />
      </el-form-item>
      <el-form-item label="配送车辆" prop="carId">
        <el-select
          v-model="form.carId"
          placeholder="请选择"
          :disabled="model === 'info'"
        >
          <el-option
            v-for="item in truckMap"
            :key="item.truckId"
            :label="item.truckCode"
            :value="item.truckId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="司机" prop="driverId">
        <el-select
          v-model="form.driverId"
          placeholder="请选择"
          :disabled="model === 'info'"
        >
          <el-option
            v-for="item in driverrMap"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="押运员" prop="escortId">
        <el-select
          v-model="form.escortId"
          placeholder="请选择"
          :disabled="model === 'info'"
        >
          <el-option
            v-for="item in driverrMap"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注">
        <el-input
          v-model="form.remark"
          placeholder="请输入"
          clearable
          :disabled="model === 'info'"
        />
      </el-form-item>
    </el-form>

    <el-row :gutter="10">
      <el-col v-if="model === 'edit'" :span="10">
        <div class="so">
          <el-input
            v-model="so.goodsName"
            placeholder="请输入商品名称"
            class="input-with-select"
          >
            <el-button
              slot="append"
              type="primary"
              icon="el-icon-search"
              @click="tableLeftFetchData"
            >搜索</el-button>
          </el-input>
        </div>
        <el-row>
          <el-col :span="8">
            <goods-tree
              class="leftTree"
              title="商品分类"
              :tree-data="treeData02"
              :loading="$loadingPlugin.getTreeData"
              :mouse-button="false"
              @currentChange="currentChange02"
            />
          </el-col>
          <el-col :span="16">
            <lb-table
              ref="lbTableLeft"
              border
              class="leftTable"
              highlight-current-row
              element-loading-text="加载中"
              :column="tableLeftData.column"
              :data="tableLeftData.data"
              @current-change="tableLeftChange"
            />
          </el-col>
        </el-row>
      </el-col>
      <el-col :span="lbTableRightwidth">
        <lb-table
          ref="lbTableRight"
          border
          class="rightTable"
          element-loading-text="加载中"
          :column="tableRightData.column"
          :data="tableRightData.data"
        />
      </el-col>
    </el-row>
    <div slot="footer" class="dialog-footer">
      <el-button v-if="model === 'edit'" type="primary" @click="save">
        保存
      </el-button>
      <el-button v-if="model === 'examine'" type="primary" @click="adopt">
        通过
      </el-button>
      <el-button v-if="model === 'examine'" type="primary" @click="reject">
        驳回
      </el-button>

      <el-button @click="visible = false">
        关闭
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import getTreeData from '@/utils/jsonTree'
  import GoodsTree from '@/views/components/GoodsTypeTree'
  import { formatColumnMap } from '@/utils'
  import {
    selectOrgSNNoAndReType,
    goodsTypeQueryList,
    goodsTypeDetailList,
    stockTransApply,
    stockTransDetail,
    stockTransCheck,
    allDriverList, // 司机查询
    truckQueryList// 车辆查询
  } from '@/api'
  export default {
    name: 'transferEdit',
    components: {
      GoodsTree
    },
    data() {
      return {
        visible: false,
        model: '',
        title: '',
        currentGoodsType: '',
        lbTableRightwidth: 14,
        form: {},
        so: {},
        storeMap: [],
        driverrMap: [],
        truckMap: [],
        treeData02: [],
        tableLeftData: {
          column: [
            {
              prop: 'gtName',
              label: '商品名称'
            },
            {
              prop: 'specName',
              label: '规格型号'
            },
            {
              prop: 'unitName',
              label: '单位'
            }
          ],
          data: []
        },
        tableRightData: {
          column: [
            {
              prop: 'gtName',
              label: '商品名称'
            },
            {
              prop: 'specName',
              label: '规格型号'
            },
            {
              prop: 'unitName',
              label: '单位'
            },
            {
              prop: 'gdStatus',
              label: '状态',
              render: (h, scope) => {
                return (
                <div>
                  {scope.row._edit ? (
                    <el-select
                      value={scope.row[scope.column.property]}
                      style='width: 80px'
                      onChange={val => {
                        scope.row[scope.column.property] = val
                      }}
                    >
                      {this.transStatusMap.map(option => {
                        return (
                          <el-option
                            label={option.desc}
                            value={option.value}
                          ></el-option>
                        )
                      })}
                    </el-select>
                  ) : (
                    <span>
                      {scope.row[scope.column.property] &&
                        formatColumnMap(
                          this.transStatusMap,
                          'value',
                          scope.row[scope.column.property],
                          'desc'
                        )}
                    </span>
                  )}
                </div>
                )
              }
            },
            {
              prop: 'gdCount',
              label: '数量',
              render: (h, scope) => {
                return (
                <div>
                  {scope.row._edit ? (
                    <el-input
                      value={scope.row[scope.column.property]}
                      onInput={val => {
                        scope.row[scope.column.property] = val
                      }}
                    ></el-input>
                  ) : (
                    <span>{scope.row[scope.column.property]}</span>
                  )}
                </div>
                )
              }
            },
            {
              prop: 'netWeight',
              label: '重量',
              render: (h, scope) => {
                return (
                <div>
                  {scope.row._edit ? (
                    <el-input
                      value={scope.row[scope.column.property]}
                      onInput={val => {
                        scope.row[scope.column.property] = val
                      }}
                    ></el-input>
                  ) : (
                    <span>{scope.row[scope.column.property]}</span>
                  )}
                </div>
                )
              }
            },
            {
              prop: 'remark',
              label: '备注',
              render: (h, scope) => {
                return (
                <div>
                  {scope.row._edit ? (
                    <el-input
                      value={scope.row[scope.column.property]}
                      onInput={val => {
                        scope.row[scope.column.property] = val
                      }}
                    ></el-input>
                  ) : (
                    <span>{scope.row[scope.column.property]}</span>
                  )}
                </div>
                )
              }
            },
            {
              label: '操作',
              width: '150px',
              fixed: 'right',
              render: (h, scope) => {
                return (
                <div>
                  {scope.row._edit ? (
                    <div>
                      <el-button
                        type='primary'
                        onClick={() => {
                          this.handleSave(scope)
                        }}
                      >
                        保存
                      </el-button>
                      <el-button
                        onClick={() => {
                          this.handleCancle(scope)
                        }}
                      >
                        取消
                      </el-button>
                    </div>
                  ) : (
                    <div>
                      <el-button
                        type='primary'
                        onClick={() => {
                          this.handleEdit(scope)
                        }}
                      >
                        编辑
                      </el-button>
                      <el-button
                        type='danger'
                        onClick={() => {
                          this.handleDel(scope)
                        }}
                      >
                        删除
                      </el-button>
                    </div>
                  )}
                </div>
                )
              }
            },
            {
              prop: 'goodsSN',
              label: '钢瓶编码'
            },
            {
              prop: 'goodsSN1',
              label: '芯片编码'
            }
          ],
          data: [],
          defaultData: []
        },
        rules: {
          transType: [
            { required: true, message: '请选择调拨类型', trigger: 'blur' }
          ],
          outStoreId: [
            { required: true, message: '请选择出库名', trigger: 'blur' }
          ],
          inStoreId: [
            { required: true, message: '请选择入库名', trigger: 'blur' }
          ],
          carId: [{ required: true, message: '请选择配送车辆', trigger: 'blur' }],
          driverId: [{ required: true, message: '请选择司机', trigger: 'blur' }],
          escortId: [{ required: true, message: '请选择押运员', trigger: 'blur' }]
        },
        transStatusMap: [
          { value: 1, desc: '重', key: 'HEAVY' },
          { value: 2, desc: '轻', key: 'LIGHT' },
          { value: 3, desc: '回收', key: 'RECYCLE' },
          { value: 4, desc: '故障', key: 'BROKEN' },
          { value: 5, desc: '已损坏', key: 'CORRUPT' },
          { value: 6, desc: '正常', key: 'NORMAL' },
          { value: 7, desc: '报废', key: 'SCRAPPED' },
          { value: 8, desc: '过期', key: 'EXPIRED' },
          { value: 9, desc: '问题重瓶', key: 'QUEHEAVY' }
        ]
      }
    },
    watch: {},
    created() {
      this.init()
      this.getTreeData02()
    },
    methods: {
      open(type, temp) {
        if (temp) {
          this.getTransferInfo(temp.stockTransCode)
          this.form = temp
          console.log(temp)
        }

        this.visible = true
        if (type === 'add') {
          this.title = `商品调拨`
          this.model = 'edit'
          this.lbTableRightwidth = 14
          this.actionDisplay(true)
        }
        if (type === 'edit') {
          this.title = `调拨单编辑`
          this.model = 'edit'
          this.lbTableRightwidth = 14
          this.actionDisplay(true)
        }
        if (type === 'info') {
          this.title = `调拨单明细`
          this.model = 'info'
          this.lbTableRightwidth = 24
          this.actionDisplay(false)
        }
        if (type === 'examine') {
          this.title = `调拨单审核`
          this.model = 'examine'
          this.lbTableRightwidth = 24
          this.actionDisplay(false)
        }
      },

      // 操作栏隐藏显示
      actionDisplay(action) {
        const column = this.tableRightData.column
        column.forEach((item, index, row) => {
          if (item.label === '操作') {
            if (action) {
              item.fixed = 'right'
            } else {
              item.fixed = 'false'
            }
          }
        })
      },

      getTransferInfo(stockTransCode) {
        stockTransDetail({
          stockTransCode
        }).then(res => {
          this.tableRightData.data = res.data.rows
          this.tableRightData.defaultData = res.data.rows
        })
      },

      reset() {
        this.form = {}
        this.so = {}
        this.tableRightData.data = []
        this.tableRightData.defaultData = []
      },

      tableLeftFetchData() {
        const gtId = this.currentGoodsType.gtId
        const json = {
          currentPage: 1,
          pageSize: 9999,
          gtId
        }
        const goodsName = this.so.goodsName
        if (goodsName) {
          json.goodsName = goodsName
        }
        goodsTypeDetailList(json).then(res => {
          this.tableLeftData.data = res.data.rows
        })
      },
      tableLeftChange(val) {
        console.log(val)
        const tableData = this.tableRightData.data
        const defaultData = this.tableRightData.defaultData
        const json = {
          gtId: val.gtId,
          gtSNNo: val.gtSNNo,
          gtName: val.gtName,
          goodsCode: val.goodsCode,
          goodsName: val.goodsName,
          goodsSpec: val.goodsSpec,
          specCode: val.specCode,
          specName: val.specName,
          unitId: val.unitId,
          unitName: val.unitName,
          tempGdStatus: val.gdStatus,
          goodsId: val.goodsId,
          pricingMode: val.pricingMode,
          remark: '',
          gdStatus: '',
          gdCount: '',
          netWeight: ''
        }
        tableData.push(json)
        defaultData.push(json)
      },
      async getTreeData02() {
        const res = await goodsTypeQueryList({})
        const data = res.data.map(item => ({
          label: item.gtName,
          ...item
        }))
        this.treeData02 = getTreeData(data)
      },
      currentChange02(current) {
        this.currentGoodsType = current
        this.tableLeftFetchData()
      },
      init() {
        selectOrgSNNoAndReType({
          currentPage: 1,
          pageSize: 9999,
          reType: 4
        }).then(res => {
          console.log(res)
          this.storeMap = res.data.rows
        })

        truckQueryList({
          currentPage: 1,
          pageSize: 9999
        }).then(res => {
          console.log(res)
          this.truckMap = res.data.rows
        })

        // queryOwnersList({
        //   utype: 512
        // }).then(res => {
        //   this.driverrMap = res.data;
        // });
        allDriverList().then(res => {
          this.driverrMap = res.data
        })
      },
      exchange() {
        const num1 = this.query.inStoreId
        const num2 = this.query.outStoreId
        const temp = num1
        this.form.inStoreId = num2
        this.form.outStoreId = temp
      },
      handleEdit(scope) {
        this.$set(scope.row, '_edit', true)
      },
      handleSave(scope) {
        this.$set(scope.row, '_edit', false)
        this.$set(
          this.tableRightData.defaultData,
          scope.$index,
          JSON.parse(JSON.stringify(scope.row))
        )
      },
      handleCancle(scope) {
        this.$set(
          this.tableRightData.data,
          scope.$index,
          JSON.parse(
            JSON.stringify(this.tableRightData.defaultData[scope.$index])
          )
        )
      },
      handleDel(scope) {
        const row = this.tableRightData.data
        const defaultRow = this.tableRightData.defaultData
        this.$delete(row, scope.$index)
        this.$delete(defaultRow, scope.$index)
      },
      save() {
        this.$refs.dataForm.validate(valid => {
          if (valid) {
            const detailList = this.tableRightData.data
            const json = { ...this.form }
            json.detailList = detailList
            const loading = this.$message({
              message: '正在执行操作',
              duration: 0,
              iconClass: 'el-icon-loading'
            })
            stockTransApply(json).then(res => {
              if (res.success) {
                this.$message({
                  message: '操作成功！',
                  type: 'success'
                })
                this.visible = false
                this.$parent.search()
              }
            }).finally(() => {
              loading.close()
            })
          } else {
            return false
          }
        })
      },
      adopt() {
        const operator = this.form.operator
        const type = 2
        stockTransCheck({
          operator,
          type
        }).then(res => {
          if (res.success) {
            this.$message({
              message: '操作成功！',
              type: 'success'
            })
            this.$parent.search()
            this.visible = false
          } else {
            this.$message({
              message: '操作失败！',
              type: 'error'
            })
          }
        })
      },
      reject() {
        const operator = this.form.operator
        const type = 1
        this.$prompt('请输入驳回原因', '提示', {
          confirmButtonText: '提交',
          cancelButtonText: '关闭'
        })
          .then(({ rejectRemark }) => {
            stockTransCheck({
              rejectRemark,
              operator,
              type
            }).then(res => {
              if (res.success) {
                this.$message({
                  message: '操作成功！',
                  type: 'success'
                })
                this.$parent.search()
                this.visible = false
              } else {
                this.$message({
                  message: '操作失败！',
                  type: 'error'
                })
              }
            })
          })
          .catch(() => {})
      }
    }
  }
</script>

<style lang="scss" scoped>
.so {
  padding: 10px;
  border: 1px solid #dfdfdf;
}
.leftTree {
  height: 50vh;
}
.aside.open {
  width: auto;
}
.leftTable {
  height: 50vh;
  overflow-y: auto;
}
.rightTable {
  width: 100%;
}
</style>
